<template>
	<view>
		<view>
			<header id="yp_header" :style="{backgroundImage: 'url(' + headerImg + ')'}"></header>

			<view class="bannerone">
				<view class="bannerpos">
					<view v-if="startError || wifiListError || getPowerError || endError" id="classList">
						<view v-if="startError" style="margin-bottom: rpx;">
							<view class='title'>
								<text>{{headerMsg}}</text>
							</view>
							<view class='error'>
								<icon type="clear" size="40" />
							</view>
							<view class='error'>
								<text>{{footerMsg}}</text>
							</view>

							<view class="manual_conn"><b>请尝试手动连接</b></view>
							<view class='info_hui'>
								<text>方法一: 点击<block><text style='color: green;'>“连接wifi”</text></block>按钮重试</text>
							</view>
							<view class='info_hui'>
								<text>方法二: 点击手机“设置”，在WLAN页面手动连接房间wifi</text>
							</view>
							<view class='info'>
								<text style="color:#333">wifi帐号: </text>
								<text>{{ssid}}</text>
							</view>
							<view class='info'>
								<text style="color:#333">wifi密码: </text>
								<text selectable class='pass'>{{pass}}</text>
							</view>
						</view>

						<view v-if="wifiListError" style="margin-bottom: rpx;">
							<view class='title'>
								<text>{{headerMsg}}</text>
							</view>
							<view class='error'>
								<icon type="cancel" size="40" />
							</view>
							<view class='error'>
								<text>{{footerMsg}}</text>
							</view>
							<view class="manual_conn"><b>请尝试手动连接</b></view>
							<view class='info_hui'>
								<text>方法一: 点击<block><text style='color: green;'>“连接wifi”</text></block>按钮重试</text>
							</view>
							<view class='info_hui'>
								<text>方法二: 点击手机“设置”，在WLAN页面手动连接房间wifi</text>
							</view>
							<view class='info'>
								<text style="color:#333">wifi帐号: </text>
								<text>{{ssid}}</text>
							</view>
							<view class='info'>
								<text style="color:#333">wifi密码: </text>
								<text selectable class='pass'>{{pass}}</text>
							</view>
						</view>
						<view v-if="getPowerError" style="margin-bottom: rpx;">
							<view class='title'>
								<text>{{headerMsg}}</text>
							</view>
							<view class='error'>
								<icon type="cancel" size="40" />
							</view>
							<view class='error'>
								<text>{{footerMsg}}</text>
							</view>
							<view class="manual_conn"><b>请点击免费取电</b></view>
						</view>

						<view v-if="endError" style="margin-bottom: rpx;">
							<view class='title'>
								<text>{{headerMsg}}</text>
							</view>
							<view class='success'>
								<icon type="success" size="40" />
							</view>
							<view class='success' style="margin-bottom: 60rpx;">
								<text style="font-size: 35rpx;">{{footerMsg}}</text>
							</view>
						</view>

						<button v-if="startError || wifiListError" class="yp_bg_theme" @click="manualStartWifi">
							连接WiFi
						</button>
						<button v-if="endError || getPowerError" class="yp_bg_theme" @click="manualGetPower">
							免费取电
						</button>
					</view>
				</view>
			</view>

			<view id="zhuanchang" :style="'margin-top: ' + marginTopPrecent">
				<view class="big_title">
					<span><em>为你推荐</em></span>
				</view>
				<ul style="padding: 0 3%;">
					<block v-for="(item, acturl) in activityUrl" :key="acturl">
						<li>
							<view @click="openMiniProgram(item)" class="activity-item">
								<img mode="widthFix" :src="item.imgUrl">
							</view>
						</li>
					</block>
				</ul>
			</view>
		</view>
	</view>
</template>

<script>
	var request = require("@/utils/request.js");
	export default {
		data() {
			return {
				startError: false, //初始化错误提示
				wifiListError: false, //wifi列表错误显示开关
				getPowerError: false,
				endError: false, //连接最后的提示
				productid: '', //设备所属产品ID-15
				deivcename: '', //设备名称-7d7KacHhZBeprOnLiYHN
				ssid: '', //wifi帐号(必填)-abc
				pass: '', //无线网密码(必填)-abc12345
				bssid: '', //设备号 自动获取
				bip: '',
				tenantUnionid: '', //用户unionid
				headerImg: 'https://iot-img.danjinwulian.com/headerImg.png',
				headerMsg: '',
				footerMsg: '',
				marginTopPrecent: '55%',

				activityUrl: [{
						imgUrl: 'https://iot-img.danjinwulian.com/chi.jpg',
						// 小程序跳转配置
						miniProgram: {
							appId: 'wxb0b2b6d17564fb6b', // 目标小程序的AppID
							path: '/pages/index/category', // 目标页面路径
							extraData: {
								id: 30
							}
						}
					},
					{
						imgUrl: 'https://iot-img.danjinwulian.com/he.jpg',
						miniProgram: {
							appId: 'wxb0b2b6d17564fb6b',
							path: '/pages/index/category',
							extraData: {
								id: 38
							}
						}
					},
					{
						imgUrl: 'https://iot-img.danjinwulian.com/wan.jpg',
						miniProgram: {
							appId: 'wxb0b2b6d17564fb6b',
							path: '/pages/index/category',
							extraData: {
								id: 41
							}
						}
					},
					{
						imgUrl: 'https://iot-img.danjinwulian.com/le.jpg',
						miniProgram: {
							appId: 'wxb0b2b6d17564fb6b',
							path: '/pages/index/category',
							extraData: {
								id: 47
							}
						}
					}
				]
			}
		},
		onLoad: function(options) {
			console.log("userName=" + options.userName + ",roomName=" + options.roomName + ",wifiName=" + options
				.wifiName + ",wifiPswd=" + options.wifiPswd)
			if (options.userName && options.roomName) {
				wx.setNavigationBarTitle({
					// title: options.userName + options.roomName
					title: options.roomName
				});
			}

			if (options.productId && options.deviceName && options.wifiName && options.wifiPswd) {
				this.setData({
					productid: options.productId,
					deivcename: options.deviceName,
					ssid: options.wifiName,
					pass: options.wifiPswd
				});
			}

			// var token = uni.getStorageSync("tenant_token")
			// if (!token) {
			// 	let msg = request.wxLogin();
			// 	if (msg && msg != '') {
			// 		uni.showToast({title:msg,icon:'error',duration: 2000});
			// 	}
			// }

			// var unionid = uni.getStorageSync("tenant_unionid")
			// if (unionid) {
			// 	this.setData({
			// 		tenantUnionid: unionid
			// 	});
			// }
		},
		onShow: function() {
			var _this = this;
			if (_this.ssid && _this.pass) {
				//检测手机型号
				var systemInfo = uni.getSystemInfoSync();
				console.log("_systemInfo: " + JSON.stringify(systemInfo))
				if (systemInfo) {
					var platform = systemInfo.platform; //系统 android/ios
					var system = ''; //版本号
					if (platform == 'android') system = parseInt(systemInfo.system.substr(8));
					if (platform == 'ios') system = parseInt(systemInfo.system.substr(4));
					console.log("platform: " + platform + ", system=" + system);

					if ((platform == 'android' && system < 6) || (platform == 'ios' && system < 11)) {
						_this.setData({
							startError: true,
							footerMsg: '手机版本暂时不支持'
						});
						return
					}

					_this.manualStartWifi();
				}
			} else {
				_this.setData({
					startError: false,
					wifiListError: true,
					endError: false,
					headerMsg: '连接房间wifi失败',
					footerMsg: '房间wifi异常，请联系酒店管理员',
					marginTopPrecent: '55%'
				});
			}
		},
		methods: {
			// 打开其他小程序
			openMiniProgram: function(item) {
				const _this = this;
				
				// 检查是否配置了小程序信息
				if (!item.miniProgram || !item.miniProgram.appId) {
					console.error('小程序配置信息不完整');
					wx.showToast({
						title: '配置信息错误',
						icon: 'none'
					});
					return;
				}
				
				// 调用微信小程序跳转API
				wx.navigateToMiniProgram({
					appId: item.miniProgram.appId, // 目标小程序的AppID
					path: item.miniProgram.path, // 目标页面路径
					extraData: item.miniProgram.extraData || {}, // 传递给目标小程序的数据
					envVersion: 'develop', // 版本类型：develop(开发版)，trial(体验版)，release(正式版)
					success: function(res) {
						console.log('跳转小程序成功', res);
					},
					fail: function(err) {
						console.error('跳转小程序失败', err);
						wx.showToast({
							title: '跳转失败',
							icon: 'none'
						});
					}
				});
			},
			manualStartWifi: function() {
				//初始化 Wi-Fi 模块
				this.startWifi();

				setTimeout(function() {
					wx.hideLoading();
				}, 10000);
			},
			manualGetPower: function() {
				//扫码开电
				this.openCircuitSwitch();

				setTimeout(function() {
					wx.hideLoading();
				}, 5000);
			},
			//1、初始化WiFi模块
			startWifi: function() {
				console.log("startWifi...")
				var _this = this;
				wx.showLoading({
					title: 'wifi连接中...'
				});
				_this.setData({
					headerMsg: '欢迎使用丹堇物联',
					footerMsg: '正在连接wifi...'
				});

				wx.startWifi({
					success: function() {
						wx.getConnectedWifi({
							success: function(res) {
								console.log("res.wifi:" + JSON.stringify(res.wifi))

								if (res.wifi.SSID === _this.ssid) {
									_this.setData({
										bssid: res.wifi.BSSID
									});
									// _this.openCircuitSwitch();
									_this.showCircuitSwitch();
								} else {
									_this.connectWifi();
								}
							},
							fail: function(res) {
								console.log(res.errCode + ":" + res.errMsg);
								_this.connectWifi();
							},
						})
					},
					fail: function(res) {
						_this.setData({
							startError: true,
							wifiListError: false,
							endError: false,
							headerMsg: '连接房间wifi失败'
						});
					}
				})
			},
			//2、连接WiFi
			connectWifi: function() {
				console.log("connectWifi...")
				var _this = this;
				wx.connectWifi({
					SSID: _this.ssid,
					// BSSID: _this.bssid,
					password: _this.pass,
					// forceNewApi: true,
					partialInfo: true,
					success(cres) {
						console.log("success:" + JSON.stringify(cres))
						// console.log("_this.productid=" + _this.productid)
						// console.log("_this.deivcename=" + _this.deivcename)

						var getConnectedWifi = true;
						wx.onWifiConnected(result => {
							console.log("onWifiConnected result: " + JSON.stringify(result))
							getConnectedWifi = false;
							if (result.wifi.SSID === _this.ssid) {
								_this.setData({
									bssid: result.wifi.BSSID
								});
								// _this.openCircuitSwitch();
								_this.showCircuitSwitch();
							} else {
								_this.setData({
									startError: true,
									wifiListError: false,
									endError: false,
									headerMsg: '连接房间wifi失败',
									footerMsg: '请打开网络重新连接房间wifi，不连会断电哦',
									marginTopPrecent: '55%'
								});
								setTimeout(function() {
									wx.hideLoading();
								}, 500);
							}
						})

						setTimeout(function() {
							if (getConnectedWifi) {
								wx.getConnectedWifi({
									success: function(res) {
										console.log("res.wifi:" + JSON.stringify(res.wifi))

										if (res.wifi.SSID === _this.ssid) {
											_this.setData({
												bssid: res.wifi.BSSID
											});
											// _this.openCircuitSwitch();
											_this.showCircuitSwitch();
										} else {
											_this.setData({
												startError: true,
												wifiListError: false,
												endError: false,
												headerMsg: '连接房间wifi失败',
												footerMsg: '请打开网络重新连接房间wifi，不连会断电哦',
												marginTopPrecent: '55%'
											});
											setTimeout(function() {
												wx.hideLoading();
											}, 500);
										}
									},
									fail: function(res) {
										console.log(res.errCode + ":" + res.errMsg);
										_this.setData({
											startError: true,
											wifiListError: false,
											endError: false,
											headerMsg: '连接房间wifi失败',
											footerMsg: '获取已连接wifi异常，请联系酒店管理员',
											marginTopPrecent: '55%'
										});
										setTimeout(function() {
											wx.hideLoading();
										}, 500);
									},
								})
							}
						}, 1500);
					},
					fail(res) {
						console.log("fail:" + JSON.stringify(res))

						var _footerMsg = '';
						if (res.errCode === 12002) {
							_footerMsg = 'wifi密码错误，请联系酒店管理员';
						} else if (res.errCode === 12003) {
							_footerMsg = 'wifi连接超时，点击“连接WiFi”重新连接';
						} else if (res.errCode === 12005) {
							_footerMsg = '请打开无线网络，点击“连接WiFi”重新连接';
						} else if (res.errCode === 12006) {
							_footerMsg = '请打开位置信息，点击“连接WiFi”重新连接';
						} else {
							_footerMsg = '无法连接房间wifi【错误码:' + res.errCode + '，错误信息：' + res.errMsg +
							'】，请联系酒店管理员';
						}

						_this.setData({
							startError: true,
							wifiListError: false,
							endError: false,
							headerMsg: '连接房间wifi失败',
							footerMsg: _footerMsg,
							marginTopPrecent: '55%'
						});
						setTimeout(function() {
							wx.hideLoading();
						}, 1500);
					}
				})
			},
			showCircuitSwitch: function() {
				var _this = this;

				setTimeout(function() {
					wx.hideLoading();
				}, 1500);

				if (wx.canIUse('getLocalIPAddress')) {
					wx.getLocalIPAddress({
						success(res) {
							_this.setData({
								bip: res.localip
							});
						}
					})
				}

				_this.setData({
					startError: false,
					wifiListError: false,
					getPowerError: false,
					endError: true,
					headerMsg: '欢迎使用丹堇物联',
					footerMsg: 'wifi已成功连接，请点击下方按钮免费取电',
					marginTopPrecent: '45%'
				});
			},
			//调用服务端电路开关修改接口，扫码开电
			openCircuitSwitch: function() {
				var _this = this;

				wx.showLoading({
					title: '免费取电中...'
				});

				console.log("局域网IP: " + _this.bip);
				uni.request({
					url: getApp().globalData.apiPath + '/mnp/device/changeCircuitSwitch',
					method: 'PUT',
					data: {
						productId: _this.productid,
						deviceName: _this.deivcename,
						deviceIp: _this.bip,
						deviceMac: _this.bssid,
						circuitSwitch: '10',
						unionid: _this.tenantUnionid
					},
					success: (res) => {
						console.log("扫码开电: " + JSON.stringify(res.data));
						if (res.data.code == 200) {
							_this.setData({
								startError: false,
								wifiListError: false,
								getPowerError: false,
								endError: true,
								headerMsg: '免费取电成功',
								footerMsg: '请保持房间wifi连接，不连则会断电哦',
								marginTopPrecent: '15%'
							});
						} else {
							_this.setData({
								startError: false,
								wifiListError: false,
								getPowerError: true,
								endError: false,
								headerMsg: '免费取电失败，点击“免费取电”重新取电',
								footerMsg: res.data.msg + '请联系酒店管理员'
							});
						}

						setTimeout(function() {
							wx.hideLoading();
						}, 1000);
					},
					fail() {
						_this.setData({
							startError: false,
							wifiListError: false,
							getPowerError: true,
							endError: false,
							headerMsg: '免费取电失败，点击“免费取电”重新取电',
							footerMsg: '免费取电失败！请联系酒店管理员'
						});

						setTimeout(function() {
							wx.hideLoading();
						}, 1000);
					},
					complete() {
						setTimeout(function() {
							wx.hideLoading();
						}, 5000);
					}
				});
			},

			setData: function(obj) {
				let that = this;
				let keys = [];
				let val, data;
				Object.keys(obj).forEach(function(key) {
					keys = key.split('.');
					val = obj[key];
					data = that.$data;
					keys.forEach(function(key2, index) {
						if (index + 1 == keys.length) {
							that.$set(data, key2, val);
						} else {
							if (!data[key2]) {
								that.$set(data, key2, {});
							}
						}

						data = data[key2];
					});
				});
			}
		}
	}
</script>

<style>
	@import "./scan-power.css";
	
	/* 活动项目点击样式 */
	.activity-item {
		cursor: pointer;
		transition: opacity 0.3s ease;
	}
	
	.activity-item:active {
		opacity: 0.7;
	}
	
	.activity-item img {
		width: 100%;
		height: auto;
		border-radius: 8px;
	}
</style>